package com.kyxx.topics.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.R;
import com.kyxx.topics.adapter.MemberAddCardAdapter;
import com.kyxx.topics.adapter.MemberSearchCardAdapter;
import com.kyxx.topics.adapter.OnTextChangeAdapter;
import com.kyxx.topics.bean.MemberAddCardBean;
import com.kyxx.topics.decoration.DividerItemDecoration;
import com.kyxx.topics.decoration.TitleItemDecoration;
import com.kyxx.topics.net.LoadingStringCallBack;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.ToastUtils;
import com.kyxx.topics.widget.ClearEditText;
import com.kyxx.topics.widget.IndexBar;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 添加会员卡
 */
public class MemberAddCardActivity extends BaseActivity implements MemberAddCardAdapter.OnItemClickLitener{
    @Bind(R.id.rv_member_add_card)
    RecyclerView rv_member_add_card;
    @Bind(R.id.indexBar)
    IndexBar indexBar;
    @Bind(R.id.et_msg_search)
    ClearEditText et_msg_search;
    @Bind(R.id.ll_add_card)
    LinearLayout ll_add_card;
    @Bind(R.id.rv_searh_card)
    RecyclerView rv_searh_card;
    @Bind(R.id.ll_search_card)
    LinearLayout ll_search_card;
    @Bind(R.id.tv_search_cancle)
    TextView tv_search_cancle;
    @Bind(R.id.tv_add_member_custom)
    TextView tv_add_member_custom;
    private LinearLayoutManager mManager;
    private List<MemberAddCardBean> bean;
    private final static int NOTIFY = 1;
    private MemberAddCardAdapter adapter;
    private MemberSearchCardAdapter searchCardAdapter;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_member_add_card);
        ButterKnife.bind(this);
        bean = new ArrayList<>();
    }

    @Override
    protected void findViewById() {

    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic() {
        getData();
        mManager = new LinearLayoutManager(this);
        rv_member_add_card.setLayoutManager(mManager);
        rv_searh_card.setLayoutManager(new LinearLayoutManager(this));
        et_msg_search.addTextChangedListener(new OnTextChangeAdapter(){
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }
        });
    }

    private void getData() {
        HttpParams params = new HttpParams();
        JSONObject obj = new JSONObject();
        params.put("json", obj.toString());
        OkGoRequest.post(UrlUtils.VIP_CARD_GET_ALL_TYPE, context, "vip_card_get_all_type", CacheMode.REQUEST_FAILED_READ_CACHE, params, new LoadingStringCallBack(MemberAddCardActivity.this,true) {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    bean = JSONObject.parseArray(result.getJSONArray("data").toString(), MemberAddCardBean.class);
                    mHandler.sendEmptyMessage(NOTIFY);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                ToastUtils.show(context, "网络错误请稍后再试");
            }
        });
    }

    Handler mHandler = new Handler() {
        @Override
        public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
            switch (msg.what) {
                case NOTIFY:
                    adapter = new MemberAddCardAdapter(context, bean);
                    adapter.setOnItemClickLitener(MemberAddCardActivity.this);
                    rv_member_add_card.setAdapter(adapter);
                    rv_member_add_card.addItemDecoration(new TitleItemDecoration(MemberAddCardActivity.this, bean).setColorTitleBg(0xfff0f0f0).setColorTitleFont(0xff575757));
                    rv_member_add_card.addItemDecoration(new DividerItemDecoration(MemberAddCardActivity.this, DividerItemDecoration.VERTICAL_LIST));
                    //使用indexBar
                    indexBar/*.setmPressedShowTextView(tvSideBarHint)//设置HintTextView*/
                            .setNeedRealIndex(false)//设置需要真实的索引
                            .setmLayoutManager(mManager)//设置RecyclerView的LayoutManager
                            .setmSourceDatas(bean);//设置数据源

                    break;
            }
            return super.sendMessageAtTime(msg, uptimeMillis);
        }
    };


    @OnClick({R.id.et_msg_search,R.id.tv_search_cancle,R.id.iv_back,R.id.tv_add_member_custom})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.et_msg_search:
                ll_add_card.setVisibility(View.GONE);
                ll_search_card.setVisibility(View.VISIBLE);
                tv_search_cancle.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_search_cancle:
                ll_add_card.setVisibility(View.VISIBLE);
                ll_search_card.setVisibility(View.GONE);
                tv_search_cancle.setVisibility(View.GONE);
                et_msg_search.setText("");
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_add_member_custom:
                startActivity(new Intent(context, CustomMemberActivity.class));
                finish();
                break;
        }
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     * @param filterStr
     */
    private void filterData(String filterStr){
        List<MemberAddCardBean> filterDateList = new ArrayList<>();

        if(TextUtils.isEmpty(filterStr)){
            filterDateList = bean;
        }else{
            filterDateList.clear();
            for(MemberAddCardBean sortModel : bean){
                String name = sortModel.getType_name();
                String namepinyin = sortModel.getMemberCardPinyin();
                if(name.indexOf(filterStr.toString()) != -1
                        || namepinyin.toLowerCase().contains(filterStr.toString().toLowerCase())
                        ||name.toLowerCase().contains(filterStr.toString().toLowerCase())){
                    filterDateList.add(sortModel);
                }
            }
        }
        searchCardAdapter = new MemberSearchCardAdapter(context,filterDateList);
        final List<MemberAddCardBean> newBean = filterDateList;
        searchCardAdapter.setOnItemClickLitener(new MemberSearchCardAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                startActivity(new Intent(context, JoinMemberActivity.class).putExtra("bean", newBean.get(position)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                finish();
            }
        });
        rv_searh_card.setAdapter(searchCardAdapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        startActivity(new Intent(context, JoinMemberActivity.class).putExtra("bean", bean.get(position)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        finish();
    }
}